package com.shankungfu.fragment;

import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.PickItemAdapter;
import com.shankungfu.bean.PickItemBean;
import com.shankungfu.bean.ProvinceBean;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.TestUtils;
import com.shankungfu.util.WebService;
import com.tendcloud.tenddata.TCAgent;

public class PickItemFragment extends Fragment implements OnClickListener {
	private static final int DATA_SUCCESS = 1;

	private ViewFlow viewFlow;
	private PickItemAdapter adapter;
	private TextView title_city;
	private RelativeLayout progressBar;
	private ImageView head_refresh_btn;
	private String city;
	public LocationClient mLocClient = null;
	public BDLocationListener mylListener = new MyLocationListener();

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case DATA_SUCCESS:

				PickItemBean pickItemBean = (PickItemBean) msg.obj;
				adapter.setData(pickItemBean.getProjectData().getAllData());
				adapter.notifyDataSetChanged();

				break;
			}

		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.pickitem_layout, null);
		initView(v);
		updateForData();
		initBDLoc();
		return v;
	}

	private void initBDLoc() {
		mLocClient = new LocationClient(getActivity().getApplicationContext());
		mLocClient.registerLocationListener(mylListener);

		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");
		option.setPriority(LocationClientOption.NetWorkFirst);
		option.setProdName("ShanKungFu");
		option.setCoorType("bd09ll"); // 只扫描一次，扫描到就使用，否则就使用默认值，除非重新启动客户端。
		option.disableCache(false);
		// option.setScanSpan(500);
		mLocClient.setLocOption(option);

		mLocClient.start();

		// 发起定位请求。请求过程是异步的，定位结果在上面的监听函数onReceiveLocation中获取。
		if (mLocClient != null && mLocClient.isStarted())
			// if //有网络，
			mLocClient.requestLocation();
		// else // 无网络
		// mLocClient.requestOfflineLocation();
		else
			Log.d("LocSDK3", "locClient is null or not started");
	}

	private void getData(String city) {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "project");
		params.add("province", city);
		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				getSuccessData();
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {
					PickItemBean pickItemBean = JSON.parseObject(content,
							PickItemBean.class);

					String url = pickItemBean.getProjectData()
							.getHome_commend().get(0).getImg_url();
					String number = pickItemBean.getProjectData()
							.getHome_commend().get(0).getJoin_number();

					TestUtils.logE("图片地址是： " + url + ", 参加人数是：" + number);

					Message msg = new Message();
					msg.what = DATA_SUCCESS;
					msg.obj = pickItemBean;
					handler.sendMessage(msg);

				}
			}

			@Override
			public void onFailure(String content) {
			}
		};
		httpclient
				.request(GlobleConstant.PICKITEM_ADD, params, responseHandler);
	}

	private void initView(View v) {

		viewFlow = (ViewFlow) v.findViewById(R.id.viewflow);
		progressBar = (RelativeLayout) v.findViewById(R.id.progressBar);
		title_city = (TextView) getActivity().findViewById(R.id.title_city);
		head_refresh_btn = (ImageView) getActivity().findViewById(R.id.head_refresh);
		title_city.setOnClickListener(this);
		head_refresh_btn.setOnClickListener(this);
		
		adapter = new PickItemAdapter(getActivity(), MainApplication.getOptions());
		viewFlow.setAdapter(adapter);
		CircleFlowIndicator indic = (CircleFlowIndicator) v
				.findViewById(R.id.viewflowindic);
		indic.setViewFlow(viewFlow);
		// indic.setLabelFor(R.drawable.ic_launcher);
		// indic.unscheduleDrawable(getResources().getDrawable(R.drawable.ic_launcher));

		viewFlow.setFlowIndicator(indic);
	}

	public class MyLocationListener implements BDLocationListener {


		

		@Override
		public void onReceiveLocation(BDLocation location) {

			if (location == null)
				return;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr城市 : ");
				sb.append(location.getCity());
			}
			mLocClient.stop();
			Log.e("TAG", "百度定位返回的数据： " + sb.toString());
			
			city = location.getProvince();
			if (TextUtils.isEmpty(city)) {
				city = MainApplication.city;
			}
			
			MainApplication.setCity(city);
			title_city.setText(city);
			TCAgent.onEvent(getActivity(), "10000",city);
			getData(MainApplication.getCity());
		}

		@Override
		public void onReceivePoi(BDLocation location) {

		}

	}
	
	private void getCityData() {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "province");
		
		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				getSuccessData();
				ProvinceBean provinceBean = (ProvinceBean) JSON.parseObject(content, ProvinceBean.class);
				String [] listData = provinceBean.getProvinceData().toArray(new String[]{});
				TestUtils.logE("省份是： " + provinceBean.getProvinceData().toString());
				showListDialog(listData);
			}

			@Override
			public void onFailure(String content) {
				getSuccessData();
			}
		};
		httpclient
				.request(GlobleConstant.PROVINCE_LIST, params, responseHandler);
	}
	
	// http://www.strongd.net/?tag=android 多选按钮，参考

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.title_city:
			getCityData();
			break;
		case R.id.head_refresh:
			updateForData();
			getData(MainApplication.getCity());
			break;
		}
	}

	private void updateForData() {
		progressBar.setVisibility(View.VISIBLE);
		viewFlow.setVisibility(View.GONE);
	}
	
	private void getSuccessData() {
		progressBar.setVisibility(View.GONE);
		viewFlow.setVisibility(View.VISIBLE);
	}
	
	

	private void showListDialog(final String[] listData) {
		AlertDialog.Builder listDia=new AlertDialog.Builder(getActivity()); 
		listDia.setTitle(null);
        listDia.setItems(listData, new DialogInterface.OnClickListener() { 
             
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
            	city =  listData[which];
            	updateForData();
            	title_city.setText(city);
            	MainApplication.setCity(city);
            	getData(city);
            	
            } 
        }); 
        listDia.create().show(); 
	}

}
